package com.dyoud.api.user.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dyoud.api.user.dto.AddUserIncomeDto;
import com.dyoud.api.user.dto.AppQueryUserIncomeDto;
import com.dyoud.core.DozerUtils;
import com.dyoud.shop.api.model.ShopInfo;
import com.dyoud.shop.api.service.ShopInfoService;
import com.dyoud.shop.api.service.ShopStatService;
import com.dyoud.user.api.model.User;
import com.dyoud.user.api.model.UserIncome;
import com.dyoud.user.api.requests.AddUserRequest;
import com.dyoud.user.api.requests.UserIncomePageQuery;
import com.dyoud.user.api.requests.UserIncomeRequest;
import com.dyoud.user.api.service.UserIncomeService;
import com.dyoud.user.api.service.UserService;
import com.github.pagehelper.PageInfo;

/***
 * 用户收益记录
 * 
 * @author wangshuaifei
 * @date 2018/03/07
 *
 */
@Service
public class UserIncomeApiService {

    @Reference
    private UserIncomeService userIncomeService;

    @Reference
    private UserService userService;

    @Reference
    private ShopInfoService shopInfoService;

    @Reference
    private ShopStatService shopStatService;

    private SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /***
     * 用户添加收益记录
     * 
     * @param dto
     * @return
     */
    public boolean addUserIncome(AddUserIncomeDto dto) {
        // 添加用户记录时，查询用户表中是否有此用户
        User user = userService.getByPhone(dto.getUserPhone());
        // 如果没有，添加此用户信息
        if (user == null) {
            user = new User();
            user.setPhone(dto.getOperatorPhone());
            user.setPayPassword(dto.getUserPhone().substring(5, dto.getUserPhone().length()));
            user.setSource(dto.getSource());
            AddUserRequest request = new AddUserRequest();
            DozerUtils.copy(user, request);
            userService.addUser(request);
            user = userService.getByPhone(dto.getUserPhone());
        }
        dto.setUserId(user.getUserId());
        ShopInfo shopinfo = shopInfoService.getByShopId(dto.getShopId());
        UserIncomeRequest request = new UserIncomeRequest();
        DozerUtils.copy(dto, request);
        // 当日收益比例 = 消费金额 / 店铺总开店成本 * 赠送比例
        BigDecimal scale = request.getInvestment().divide(shopinfo.getCostsPrice(), 6, BigDecimal.ROUND_HALF_UP).multiply(shopinfo.getScale())
                .multiply(new BigDecimal(100));
        request.setIncomeScale(scale);
        // 收益权价值 (就是当次消费金额，根据商家规定的赠送比例，占店铺进这个商品金额的多少)
        // 收益权价值 = 消费金额 * 店铺的赠送比例
        request.setIncomeValue(request.getInvestment().multiply(shopinfo.getScale()));
        // 修改店铺剩余成本
        shopinfo.setResidueCostsPrice(shopinfo.getResidueCostsPrice().subtract(request.getIncomeValue()));
        userIncomeService.addUserIncome(request);
        // 修改店铺信息
        shopInfoService.updateShopInfoByResidueCostsPrice(shopinfo.getShopId(), shopinfo.getResidueCostsPrice());

        UserIncome userIncome = new UserIncome();
        DozerUtils.copy(request, userIncome);
        // 统计用户数据信息
        shopStatService.calcByUserIncome(userIncome);
        return true;
    }

    /***
     * 根据商户id查询用户收益记录,倒序根据创建时间查询
     * 
     * @param shopId
     * @return
     */
    public PageInfo<UserIncome> selectByShopIdOrderByCreateTime(Integer pageNo, Integer pageSize, AppQueryUserIncomeDto appQueryUserIncomeDto) {
        UserIncomePageQuery pageQuery = new UserIncomePageQuery();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setShopId(appQueryUserIncomeDto.getShopId());
        pageQuery.setState(appQueryUserIncomeDto.getState());
        try {
            StringBuffer beginDate = new StringBuffer(appQueryUserIncomeDto.getBeginDate());
            beginDate.append(" 00:00:00");
            StringBuffer endDate = new StringBuffer(appQueryUserIncomeDto.getEndDate());
            endDate.append(" 23:59:59");
            pageQuery.setBeginDate(dateFormate.parse(beginDate.toString()));
            pageQuery.setEndDate(dateFormate.parse(endDate.toString()));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // type=1，查询时间间隔中的用户收益，type=2，根据月份查询用户收益
        switch (appQueryUserIncomeDto.getType()) {
        case 1:
            return userIncomeService.selectByShopIdAndCreateTimeOrIntervalOrderByCreateTime(pageQuery);
        case 2:
            return userIncomeService.selectByShopIdAndCreateTimeOrderByCreateTime(pageQuery);
        default:
            return userIncomeService.selectByShopIdOrderByCreateTime(pageQuery);
        }

    }

    /***
     * 根据商户id查询所有用户消费记录，根据userId汇总
     * 
     * @param shopId
     * @return
     */
    public PageInfo<UserIncome> selectByShopIdGroupByUserId(Integer pageNo, Integer pageSize, Long shopId) {
        UserIncomePageQuery pageQuery = new UserIncomePageQuery();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setShopId(shopId);
        //先默认查询已经收益的用户记录,需要变在修改
        pageQuery.setState(1);
        return userIncomeService.selectByShopIdGroupByUserId(pageQuery);
    }
    // 不写中文的话，光参数就有点整懵逼了
    
      public static void main(String[] args) { 
          BigDecimal 开店成本 = new BigDecimal("2000000"); 
          BigDecimal 赠送比例 = new BigDecimal("0.90"); 
          BigDecimal 当天消费 = new BigDecimal("3.33"); 
          BigDecimal 占啥总额比例 = 当天消费.divide(开店成本, 7, BigDecimal.ROUND_FLOOR); 
          System.out.println("那个啥 的比例："+占啥总额比例.multiply(赠送比例)); 
          /*BigDecimal 具体赠送金额 = 开店成本.multiply(赠送比例); 
          System.out.println("具体赠送金额："+具体赠送金额); */
          BigDecimal 当日收益比例 = 当天消费.divide(开店成本,7,BigDecimal.ROUND_FLOOR).multiply(赠送比例).multiply(new BigDecimal(100)); 
          System.out.println("当日收益比例:"+当日收益比例); 
      }
     
}
